import { login, getUserInfo, getUserDetail } from '@/api/user'
import { getToken, setToken, removeToken, setTime } from '@/utils/auth'
import { resetRouter } from '@/router'
const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  updatePhoto(state, photo) {
    state.userInfo.staffPhoto = photo
  },
  setToken(state, token) {
    state.token = token
    setToken(token)
    setTime(Date.now())
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  setUserInfo(state, payload) {
    state.userInfo = payload
    // console.log(payload)
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  async login({ commit }, payload) {
    const data = await login(payload)
    // console.log(data)
    commit('setToken', data)
  },
  async getUserInfo({ commit }) {
    const data = await getUserInfo()
    const data2 = await getUserDetail(data.userId)
    // data2.staffPhoto = 'abccdddf.png'
    const result = {
      ...data,
      ...data2
    }
    commit('setUserInfo', result)
    return result
  },
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
    // 重置路由
    resetRouter()
    // 左侧菜单数据也重置
    // 默认模块会在当前命名中间查找。
    // root: true代表mutations从根命名空间中查看
    context.commit('permission/setRoutes', [], { root: true })

    // 重置主题色
    context.commit('settings/resetTheme', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
